import React, { useState, useEffect } from 'react';
import { Button, Modal, App, Popover, Checkbox } from 'antd';
import { GetGroupTreeList, SetPoliciesReq } from '@/common/types/org';
import orchestrationService from '@/api/services/orchestrationService';
import orgService from '@/api/services/orgService';
import PersonnelModal from '@/components/personnel-modal/personnel-modal';
import KnowPermissionsModal from '@/components/know-permissions-modal/know-permissions-modal';
import useModal from '@/hooks/use-modal/useModal';
import {
  DataDemoType,
  DefaultValueProps,
  Option,
} from '@/pages/app-permission-manage/components/AppPermissionContent';
import { SubmitType } from '@/components/personnel-modal/personnel-modal';
import TipsModals from '@/components/modals/TipsModals';
import { CloseOutlined, RightOutlined, LoadingOutlined } from '@ant-design/icons';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import { AppType, AppWorkbenchType, UserRoleEnum } from '@/common/app/constants';
import { useRouter } from '@/router/hooks';
import { useWorkBench } from '@/store/configStore';
import dayjs from 'dayjs';
import { SvgIcon } from '@/components/icon';
import { Radio, RadioGroup } from '@/components/eai-design';
import { PublishTypeEnum } from '@/types/app/type';

interface PublishComponentProps {
  appId: string;
  onSave: (
    is_publish?: boolean,
    permissionConfig?: SetPoliciesReq['statements'],
    is_all_can_qa?: boolean,
    publishType?: PublishTypeEnum,
  ) => Promise<void>;
  onCheck?: () => boolean;
  onSwitchToKnowledgeTab?: (tab: string) => void;
  isWorkflow?: boolean;
  lastAutoSaveTime?: string | null;
}

const PublishComponent: React.FC<PublishComponentProps> = ({
  appId,
  onSave,
  onCheck,
  onSwitchToKnowledgeTab,
  isWorkflow = false,
  lastAutoSaveTime = '',
}) => {
  const { message } = App.useApp();
  const [publishModalVisible, setPublishModalVisible] = useState(false);
  const [popoverVisible, setPopoverVisible] = useState(false);
  const [selectedVisibility, setSelectedVisibility] = useState<string | null>(null);
  const [publishButtonEnabled, setPublishButtonEnabled] = useState(false);
  const [datasetCheckModalVisible, setDatasetCheckModalVisible] = useState(false);
  const [publishStatus, setPublishStatus] = useState(false);
  const [selectUser, setSelectUser] = useState<SubmitType[] | DefaultValueProps[]>([]);
  const [defaultValue, setDefaultValue] = useState<DataDemoType['tableData']>([]);
  const [option, setOption] = useState<Option[]>([]);
  const [lastPublishText, setLastPublishText] = useState('');
  const [publishType, setPublishType] = useState<PublishTypeEnum>(PublishTypeEnum.workflow);

  const modal = useModal('update', 'personnel', 'delete', 'edit');
  const {
    userRole,
    appDetail: appDetailStore,
    configurations,
    isPublishTemplate,
    setIsPublishTemplate,
    isInOrchestrationPage,
  } = useOrchestrationStore();
  const router = useRouter();
  const workbench = useWorkBench();
  const isDisableDataset =
    configurations?.find((config) => config.name === 'disable_dataset')?.default_value === '1' ||
    false;

  const isPublishDirectly =
    isDisableDataset || isWorkflow || appDetailStore?.appType == AppType.fusion;

  const isEnableFunctionCalling = configurations?.find(
    (config) => config.name === 'enable_function_calling',
  );

  useEffect(() => {
    const fetchHistory = async () => {
      try {
        if (!popoverVisible) {
          return;
        }
        setIsPublishTemplate(false);
        const res = await orchestrationService.getAppPublishHistory(appId);
        const list = res?.version_list || [];
        const listPublish = list.filter((item: any) => item.is_publish);
        if (!listPublish.length) {
          setLastPublishText('当前应用未发布');
        } else {
          // 取最近一次发布时间
          const last = listPublish[0];
          const now = dayjs();
          const lastTime = dayjs.utc(last.time).tz('Asia/Shanghai');
          console.log(now, lastTime);
          const diffDays = now.diff(lastTime, 'day');
          const diffHours = now.diff(lastTime, 'hour');
          const diffMinutes = now.diff(lastTime, 'minute');

          if (diffDays > 0) {
            setLastPublishText(`发布于 ${diffDays}天前`);
          } else if (diffHours > 0) {
            setLastPublishText(`发布于 ${diffHours}小时${diffMinutes % 60}分钟前`);
          } else if (diffMinutes > 0) {
            setLastPublishText(`发布于 ${diffMinutes}分钟前`);
          } else {
            setLastPublishText('刚刚发布');
          }
        }
      } catch (e) {
        console.error(e);
        setLastPublishText('');
      }
    };
    fetchHistory();
  }, [appId, popoverVisible]);

  const formatDataset = (value: any[]): Option[] => {
    return value.map((item) => {
      return {
        key: item._id,
        value: item._id,
        type: item.type,
        label: item.name,
        name: item.name,
        children: item.children ? formatDataset(item.children) : [],
        parentId: item.parentId,
      };
    });
  };

  // const getDataset = async () => {
  //   try {
  //     const data = orgService.getDataset(appId);

  //     const dataset = (await data).list.filter((item) => item.type !== 'function');
  //     const functionDataset = (await data).list.filter((item) => item.type === 'function');

  //     const formatDatasetData = formatDataset(dataset);
  //     const formatFunctiontData = formatDataset(functionDataset);

  //     setOption([
  //       {
  //         key: 'database',
  //         value: 'databaseRoot',
  //         type: '*',
  //         label: '知识库文件',
  //         name: '知识库文件',
  //         children: formatDatasetData,
  //         isLeaf: false,
  //         parentId: null,
  //       },
  //       {
  //         key: 'function',
  //         value: 'functionRoot',
  //         type: '*',
  //         label: '数据接口',
  //         name: '数据接口',
  //         children: formatFunctiontData,
  //         isLeaf: false,
  //         parentId: null,
  //       },
  //     ]);
  //   } catch (e) {
  //     console.log(e);
  //   }
  // };

  const getDataset = async () => {
    try {
      const data = orgService.getDataset({ appId: appId });

      const dataset = (await data).list.filter((item) => item.type !== 'function');
      const functionDataset = (await data).list.filter((item) => item.type === 'function');

      const formatDatasetData = formatDataset(dataset);
      const formatFunctiontData = formatDataset(functionDataset);

      let optionsKnow = [
        {
          key: 'dataset',
          value: 'datasetRoot',
          type: 'dataset',
          label: '知识库文件',
          name: '知识库文件',
          children: formatDatasetData,
          isLeaf: false,
          parentId: null,
        },
        {
          key: 'function',
          value: 'functionRoot',
          type: 'function',
          label: '数据接口',
          name: '数据接口',
          children: formatFunctiontData,
          isLeaf: false,
          parentId: null,
        },
      ];

      if (!(!isInOrchestrationPage || isEnableFunctionCalling)) {
        optionsKnow = optionsKnow.filter((item) => item.type === 'dataset');
      }
      setOption(optionsKnow);
    } catch (e) {
      console.log(e);
    }
  };

  // 处理发布按钮点击
  const handlePublishButtonClick = async () => {
    try {
      setPublishStatus(true);
      if (onCheck && !onCheck()) {
        return;
      }

      // // 获取最新配置的问答用户
      // const appDetail = await orchestrationService.getAppDetailV2(appId, AppWorkbenchType.manage);
      // const permissionConfig = appDetail.permission_config || [];
      // const currentPermissionConfig = permissionConfig.map((item) => ({
      //   id: item.target?.target_id,
      //   name: item.target?.target_name,
      //   type: item.target?.target_type,
      //   resources: item.resources,
      // }));
      // setDefaultValue(currentPermissionConfig);

      // 问答人员已配置，直接发布
      const res = await orgService.getPolicies({ app_id: appId });
      console.log('res', res);
      if (res.length > 0 || publishType === PublishTypeEnum.plugin) {
        setPublishModalVisible(false);
        setSelectedVisibility(null);
        setPublishButtonEnabled(false);
        await onSave(true, undefined, undefined, publishType);
        return;
      }

      if (appDetailStore?.appType == AppType.fusion || isDisableDataset) {
        setPublishModalVisible(true);
        return;
      }

      // 知识库管理者仅发布知识库
      if (userRole !== UserRoleEnum.admin) {
        await onSave(true, undefined, undefined, publishType);
        return;
      }

      // await new Promise(resolve => setTimeout(resolve, 10000));

      getDataset();

      // 获取最新的 datasetStats
      const latestDatasetStats = await orchestrationService.getDatasetCount(appId);

      // 检查知识库是否为空
      if (!latestDatasetStats?.count || latestDatasetStats.count === 0) {
        !isWorkflow && onSwitchToKnowledgeTab
          ? setDatasetCheckModalVisible(true)
          : setPublishModalVisible(true);
      } else {
        setPublishModalVisible(true);
      }
    } catch (error) {
      console.error('获取知识库统计信息失败:', error);
    } finally {
      setPopoverVisible(false);
      setPublishStatus(false);
    }
  };

  const handleVisibilityChange = (value: string) => {
    setSelectedVisibility(value);
    setPublishButtonEnabled(true);
  };

  const handlePublish = async () => {
    if (!publishButtonEnabled) return;

    if (selectedVisibility === 'private') {
      // 如果选择了部分用户可见，则打开用户选择弹窗
      setPublishModalVisible(false);
      modal.update.open();
      return;
    } else {
      if (isPublishDirectly) {
        try {
          // 调用保存方法，传入 is_publish 为 true
          await onSave(true, [], true);

          // 发布成功后关闭弹窗并重置状态
          setPublishModalVisible(false);
          setSelectedVisibility(null);
          setPublishButtonEnabled(false);

          // 刷新历史记录列表
          // @ts-ignore
          if (window.__refreshCloudHistory) {
            // @ts-ignore
            window.__refreshCloudHistory();
          }
        } catch (error) {
          console.error('发布失败:', error);
          message.error('发布失败');
        }
        return;
      }

      const res = await orgService.getOrgGroupTreeList('');
      const orgGroups =
        res?.map((item) => ({
          ...item,
          type: 'group' as const,
        })) || [];
      const childrenGroups =
        res?.reduce((acc: SubmitType[], curr: GetGroupTreeList) => {
          const childrenWithType = (curr.children || []).map((child) => ({
            ...child,
            type: 'group' as const,
          }));
          return [...acc, ...childrenWithType];
        }, []) || [];
      const flattenedGroups = [...orgGroups, ...childrenGroups];
      // const flattenedGroups = [...childrenGroups];
      if (flattenedGroups.length > 0) {
        setPublishModalVisible(false);
        setSelectUser(flattenedGroups as unknown as SubmitType[]);
        modal.personnel.open();
      } else {
        try {
          // 调用保存方法，传入 is_publish 为 true
          await onSave(true, [], true);

          // 发布成功后关闭弹窗并重置状态
          setPublishModalVisible(false);
          setSelectedVisibility(null);
          setPublishButtonEnabled(false);
        } catch (error) {
          console.error('发布失败:', error);
          message.error('发布失败');
        }
      }
      return;
    }

    // try {
    //   // 调用保存方法，传入 is_publish 为 true
    //   await onSave(true);

    //   // 发布成功后关闭弹窗并重置状态
    //   setPublishModalVisible(false);
    //   setSelectedVisibility(null);
    //   setPublishButtonEnabled(false);
    // } catch (error) {
    //   console.error('发布失败:', error);
    //   message.error('发布失败');
    // }
  };

  const handlePersonnelSubmit = (value: SubmitType[]) => {
    if (isPublishDirectly) {
      // 将 SubmitType[] 转换为 SetPoliciesReq['statements'] 格式
      const statements = value.map((item) => ({
        target: {
          target_id: item.id,
          target_type: item.type,
        },
        resources: [
          {
            action: 'qa',
            resource_id: '*',
            resource_type: '*',
          },
        ],
      }));

      console.log('转换后的权限配置:', statements);
      onSave(true, statements);
      modal.personnel.close();
      modal.update.close();
      return;
    } else {
      console.log(value);
      setSelectUser(value);
      modal.personnel.open();
    }
  };

  const handleKnowSubmit = async (value: SetPoliciesReq['statements']) => {
    try {
      setPublishStatus(true);
      console.log('value', value);
      await onSave(true, value, selectedVisibility === 'public');
      modal.personnel.close();
      modal.update.close();
    } catch (error) {
    } finally {
      setPublishStatus(false);
    }
  };

  // 发布Modal内容
  const publishModalContent = (
    <div className="p-4">
      <div className="mt-4 flex justify-center gap-4">
        <div
          className={`flex cursor-pointer flex-col items-center justify-center ${
            selectedVisibility === 'public'
              ? `border-[var(--brand-color)] text-[var(--brand-color)]`
              : 'border-[#00000014] text-black'
          }`}
          style={{
            width: 185,
            height: 166,
            borderRadius: 10,
            borderWidth: 1,
            background: '#F8F8FB',
          }}
          onClick={() => handleVisibilityChange('public')}
        >
          <div className="mb-2 text-lg">所有人员可问答</div>
        </div>
        <div
          className={`flex cursor-pointer flex-col items-center justify-center ${
            selectedVisibility === 'private'
              ? 'border-[var(--brand-color)] text-[var(--brand-color)]'
              : 'border-[#00000014] text-black'
          }`}
          style={{
            width: 185,
            height: 166,
            borderRadius: 10,
            borderWidth: 1,
            background: '#F8F8FB',
          }}
          onClick={() => handleVisibilityChange('private')}
        >
          <div className="mb-2 text-lg">部分人员可问答</div>
        </div>
      </div>
    </div>
  );

  const popoverContent = (
    <div className="flex w-[320px] flex-col gap-2 p-2">
      <div className="text-left text-sm font-font-weight-400 text-text-3">{lastPublishText}</div>
      {lastAutoSaveTime && (
        <div className="color-[#4E5969] mb-2 text-sm">
          {lastAutoSaveTime ? '已自动保存 ' + lastAutoSaveTime : ''}
        </div>
      )}

      {isWorkflow && (
        <div className="mb-2 flex flex-col items-start justify-center rounded-md bg-fill-1 p-4">
          <RadioGroup
            style={{ gap: 8, display: 'flex', flexDirection: 'column', alignItems: 'start' }}
            value={publishType}
            onChange={(e) => setPublishType(e.target.value)}
            options={[
              { value: PublishTypeEnum.workflow, label: '发布为工作流' },
              { value: PublishTypeEnum.plugin, label: '发布为插件' },
            ]}
          />
        </div>
      )}
      <Button
        type="primary"
        className="flex w-full items-center justify-center bg-[#4E5969] hover:bg-[#384047]"
        style={{ borderRadius: '4px' }}
        onClick={handlePublishButtonClick}
        loading={publishStatus}
      >
        发布
      </Button>
      {(!isWorkflow || publishType === PublishTypeEnum.workflow) && (
        <div className="mt-2 flex items-center justify-center gap-2">
          <Checkbox
            checked={isPublishTemplate}
            onChange={(e) => setIsPublishTemplate(e.target.checked)}
            disabled={publishStatus}
          >
            成为公共模板
          </Checkbox>
        </div>
      )}
    </div>
  );

  return (
    <>
      {appDetailStore?.appType === AppType.fusion ? (
        <Button
          type="primary"
          className="flex items-center bg-[#4E5969] hover:bg-[#384047]"
          onClick={async () => {
            if (onCheck && !onCheck()) {
              return;
            }
            // if (appDetailStore?.fusionApp?.length == 0) {
            //   message.warning('融合应用未配置！')
            //   return
            // }

            // // 获取最新配置的问答用户
            // orchestrationService.getAppDetailV2(appId, AppWorkbenchType.manage).then((res) => {
            //   const permissionConfig = res.permission_config || [];
            //   const currentPermissionConfig = permissionConfig.map((item) => ({
            //     id: item.target?.target_id,
            //     name: item.target?.target_name,
            //     type: item.target?.target_type,
            //     resources: item.resources,
            //   }));
            //   setDefaultValue(currentPermissionConfig);
            // })

            // 问答人员已配置，直接发布
            try {
              setPublishStatus(true);
              const res = await orgService.getPolicies({ app_id: appId });
              console.log('res', res);
              if (res.length > 0) {
                setPublishModalVisible(false);
                setSelectedVisibility(null);
                setPublishButtonEnabled(false);
                await onSave(true);
                return;
              }

              setPublishModalVisible(true);
            } catch (error) {
              console.error('获取问答人员权限失败:', error);
            } finally {
              setPublishStatus(false);
            }
          }}
          icon={publishStatus ? <LoadingOutlined /> : <SvgIcon icon="ai-orch-publish" size={16} />}
        >
          发布
          {/* <div className="flex items-center justify-center">
            {publishStatus ? <LoadingOutlined /> : <RightOutlined />}
          </div> */}
        </Button>
      ) : (
        <Popover
          content={popoverContent}
          trigger="click"
          open={popoverVisible}
          onOpenChange={setPopoverVisible}
          placement="bottomRight"
          arrow={false}
          styles={{
            root: {
              paddingTop: 16,
            },
          }}
        >
          <Button
            type="primary"
            className="flex items-center bg-[#4E5969] hover:bg-[#384047]"
            icon={
              <div className="flex items-center justify-center">
                <SvgIcon icon="ai-orch-publish" size={16} />
              </div>
            }
          >
            发布
            {/* <div className="flex items-center justify-center">
              <RightOutlined />
            </div> */}
          </Button>
        </Popover>
      )}

      {/* 知识库检查弹窗 */}
      <TipsModals
        title={null}
        children={<div>未配置知识库可能会影响问答质量</div>}
        open={datasetCheckModalVisible}
        onOk={() => {
          setDatasetCheckModalVisible(false);
          onSwitchToKnowledgeTab?.('knowledge');
        }}
        onCancel={() => {
          setDatasetCheckModalVisible(false);
          setPublishModalVisible(true);
        }}
        okText="去添加"
        cancelText="仍然发布"
        headerHeight={100}
        height={100}
        footerHeight={100}
        closeIcon={
          <div
            onClick={(e) => {
              e.stopPropagation();
              setDatasetCheckModalVisible(false);
            }}
          >
            <CloseOutlined style={{ fontSize: '16px', color: '#6C7180' }} />
          </div>
        }
      ></TipsModals>
      {/* <Modal
        title={null}
        open={datasetCheckModalVisible}
        onCancel={() => setDatasetCheckModalVisible(false)}
        footer={null}
        width={424}
        // height={205}
        maskClosable={false}
        centered
        closable={true}
      >
        <div className="flex flex-col items-center pt-6">
          <div className="mb-6 text-center font-medium">未配置知识库可能会影响问答质量</div>
          <div className="flex justify-center gap-4">
            <Button
              style={{
                height: 40,
                borderRadius: 50,
                minWidth: 100,
                background: '#F6F7F9',
                border: 'none',
                color: '#333',
              }}
              onClick={() => {
                setDatasetCheckModalVisible(false);
                setPublishModalVisible(true);
              }}
            >
              仍然发布
            </Button>
            <Button
              type="primary"
              style={{
                height: 40,
                borderRadius: 50,
                minWidth: 100,
                background: '#7B67EE',
                border: 'none',
              }}
              className="hover:bg-[#6857D6]"
              onClick={() => {
                setDatasetCheckModalVisible(false);
                onSwitchToKnowledgeTab?.();
              }}
            >
              去添加
            </Button>
          </div>
        </div>
      </Modal> */}

      {/* 问答人员未配置弹窗 */}
      <TipsModals
        title={null}
        children={<div>用户问答权限未配置，前往添加</div>}
        open={publishModalVisible}
        onOk={() => {
          console.log('onOk');
          setPublishModalVisible(false);
          onSwitchToKnowledgeTab?.('permission');
        }}
        onCancel={() => {
          setPublishModalVisible(false);
          setSelectedVisibility(null);
          setPublishButtonEnabled(false);
        }}
        okText="去添加"
        // cancelText="仍然发布"
        headerHeight={100}
        height={100}
        footerHeight={100}
        closeIcon={
          <div
            onClick={(e) => {
              e.stopPropagation();
              setPublishModalVisible(false);
              setSelectedVisibility(null);
              setPublishButtonEnabled(false);
            }}
          >
            <CloseOutlined style={{ fontSize: '16px', color: '#6C7180' }} />
          </div>
        }
      ></TipsModals>

      {/* 发布选项弹窗 */}
      <Modal
        title={
          <div className="justify-left flex items-center text-[14px] font-medium text-[#474C5F]">
            发布-选择可问答人员
          </div>
        }
        open={false}
        destroyOnClose
        onCancel={() => {
          setPublishModalVisible(false);
          setSelectedVisibility(null);
          setPublishButtonEnabled(false);
        }}
        footer={
          <div className="mt-4 flex justify-center gap-4">
            <Button
              key="cancel"
              // style={{
              //   height: 40,
              //   borderRadius: 50,
              //   minWidth: 100,
              // }}
              onClick={() => {
                setPublishModalVisible(false);
                setSelectedVisibility(null);
                setPublishButtonEnabled(false);
              }}
            >
              取消
            </Button>
            <Button
              key="publish"
              type="primary"
              // style={{
              //   height: 40,
              //   borderRadius: 50,
              //   minWidth: 100,
              //   background: publishButtonEnabled ? '#7B67EE' : '#C4B4FF',
              //   border: 'none',
              // }}
              className="hover:bg-[#6857D6]"
              onClick={async () => {
                try {
                  setPublishStatus(true);
                  await handlePublish();
                } catch (error) {
                } finally {
                  setPublishModalVisible(false);
                  setPublishStatus(false);
                }
              }}
              disabled={!publishButtonEnabled}
              loading={publishStatus}
            >
              {selectedVisibility === 'private' ? '下一步' : isPublishDirectly ? '发布' : '下一步'}
            </Button>
          </div>
        }
        width={723}
        height={466}
        maskClosable={false}
        centered
      >
        {publishModalContent}
      </Modal>

      <PersonnelModal
        title="选择问答人员"
        appId={appId}
        onSubmit={handlePersonnelSubmit}
        isCheckBox={true}
        open={modal.update.isOpen}
        onCancel={modal.update.close}
        confirmLoading={modal.update.isLoading}
        defaultValue={defaultValue}
        okText={isPublishDirectly ? '发布' : '下一步'}
        destroyOnHidden
      />

      <KnowPermissionsModal
        open={modal.personnel.isOpen}
        onCancel={modal.personnel.close}
        userData={selectUser}
        options={option}
        onSubmit={handleKnowSubmit}
        isWorkflow={isPublishDirectly}
        okText="发布并完成"
        confirmLoading={publishStatus}
        isKnow={!isInOrchestrationPage || isEnableFunctionCalling ? true : false}
        destroyOnHidden
      />
    </>
  );
};

export default PublishComponent;
